package snooker.scoreboard.frame;

import java.util.LinkedList;
import java.util.List;

import snooker.scoreboard.ball.Ball;
import snooker.scoreboard.entity.Type;
import snooker.scoreboard.persistence.SnookerSharedPreferences;

import android.os.SystemClock;
import android.util.Log;

public class FrameScoreHistory {
	private static final String LOG_TAG = "FrameHistory";
	private List<Score> scoreList;
	private long startTime;
	private boolean save = true;
	
	public FrameScoreHistory() {
		scoreList = new LinkedList<Score>();
		startTime = SystemClock.elapsedRealtime();
	}
	
	public FrameScoreHistory(List<Score> history) {
		this.scoreList = history;
		startTime = SystemClock.elapsedRealtime();;
	}
	
	public void addScore(int playerId, int frameId, Type type, int breakId,
			Ball ball, int score, boolean isLuckyShot) {
		long offset = SystemClock.elapsedRealtime() - startTime;
		Score newState = new Score(playerId, frameId, type, 
				Type.Foul.equals(type) ? 0 : breakId, 
				ball, score, offset, isLuckyShot);
		Log.i(LOG_TAG, "add to history: " + newState.toString());
		scoreList.add(newState);
		if (save) {
			SnookerSharedPreferences.getInstance().saveScore(newState);
		}
	}
	
	public void addScore(Score score) {
		startTime = SystemClock.elapsedRealtime() - score.getEventTime();
		scoreList.add(score);
	}
	
	public long getStartTime() {
		return startTime;
	}
	
	public void setStartTime(long startTime) {
		this.startTime = startTime;
	}
	
	public List<Score> getScoreList() {
		return scoreList;
	}
	
	public Score getLastScore() {
		if (scoreList.size() > 0) {
			return scoreList.get(scoreList.size() - 1);
		} else {
			return null;
		}
	}
	
	public void undo() {
		Log.i(LOG_TAG, "<<<<<<<<<<<<<<<< UNDO >>>>>>>>>>>>>>>>");
		if (scoreList.size() > 0) {
			scoreList.remove(scoreList.size() - 1);
			SnookerSharedPreferences.getInstance().removeLastScore();
		}
	}
	
	public void debug() {
		for (Score fs: scoreList) {
			Log.i(LOG_TAG, "HState=" + fs.toString());
		}
	}
	
	public void setSave(boolean save) {
		this.save = save;
	}
}
